//
//  HeadLine.m
//  微看
//
//  Created by 吴明磊 on 15/8/19.
//  Copyright © 2015年 wuminglei. All rights reserved.
//

#import "HeadLine.h"
#import "NetworkTools.h"
#import "UIImageView+WebCache.h"

@implementation HeadLine


+ (void)loadInformation:(void (^)(NSArray *))information Error:(void (^)(NSError *))Error{

  [[NetworkTools sharedNetwork]loadInformation:^(NSDictionary *info) {
      
      if (info) {
          
          NSArray *infoArray = info[@"data"];
          
          NSMutableArray *tempArray = [NSMutableArray array];
          
          for (NSDictionary *dic in infoArray) {
              
              [tempArray addObject:[HeadLine headLineWithDict:dic]];
          }
          
          
          [self imageCache:information result:tempArray.copy];
      }
      
  } Error:^(NSError *error) {
      
      if (error) {
          
          Error(error);
      }
      
  }];
}

+ (void)imageCache:(void (^)(NSArray *))information result:(NSArray *)array {

    
   dispatch_group_t group =  dispatch_group_create();
    
    for (HeadLine *head in array) {
        
        NSString *url = head.pics[0];
        
        if (!url) {
            
            continue;
        }
        
        dispatch_group_enter(group);
        
        [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:url] options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            if (error) {
                
                dispatch_group_leave(group);
                return ;
            }
            
            head.imageCache = image;
            
            dispatch_group_leave(group);
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        information(array);
    });
    
}



/// 字典转模型
+ (instancetype)headLineWithDict:(NSDictionary *)dict {

    
    HeadLine *headLine = [[self alloc]init];
    
    [headLine setValuesForKeysWithDictionary:dict];
    
    return headLine;
    
}

- (void)setValue:(nullable id)value forUndefinedKey:(nonnull NSString *)key {}

- (void)setValue:(nullable NSDictionary *)value forKey:(nonnull NSString *)key {

[super setValue:value forKey:key];
    
    
    if ([key isEqualToString:@"counter"]) {
        
        NSDictionary *dic = value[key][@"data"];
        
        self.counter = [Counter counterWithDict:dic];
    }
    
    if ([key isEqualToString:@"comments"]) {
        
        NSArray *commentArray = value[@"data"];
    
        
        NSMutableArray *tempArray = [NSMutableArray array];
        
        self.comments = [[NSArray alloc]init];
        
        for (NSDictionary *dict in commentArray) {
            
            [tempArray addObject:[Comments commentWithDict:dict]];
        }
        
        self.comments = [tempArray copy];
        
    
    }
    
    
    
}

@end
